package com.freedy.concurrent.Monitors.patterns;

import com.freedy.concurrent.Monitors.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 同步模式之交替输出
 * 固定顺序
 * 使用 ReentrantLock实现
 *
 * @author Freedy
 * @date 2021/4/22 22:31
 */
@Slf4j
public class SequenceControlAlternatelyReentrant {
    private static final ReentrantLock LOCK = new ReentrantLock();
    private static final Condition a = LOCK.newCondition();
    private static final Condition b = LOCK.newCondition();
    private static final Condition c = LOCK.newCondition();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> print("A", a, b), "T1");
        Thread t2 = new Thread(() -> print("B", b, c), "T2");
        Thread t3 = new Thread(() -> print("C", c, a), "T3");

        t1.start();
        t2.start();
        t3.start();
        Sleeper.sleep(0.1);
        try {
            LOCK.lock();
            a.signal();
        } finally {
            LOCK.unlock();
        }
    }

    private static void print(String str, Condition current, Condition next) {
        for (int k = 0; k < 3; k++) {
            LOCK.lock();
            try {
                current.await();
                log.info(str);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                LOCK.unlock();
            }
        }
    }

}
